package com.yfp.group.redisDelay;

import com.yfp.common.core.constant.CacheConstants;
import com.yfp.common.redis.utils.RedisDelayQueueUtil;
import com.yfp.group.service.EnterpriseOrderService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.TimerTask;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisDelayQueueRunner implements CommandLineRunner {

    @Resource
    private RedisDelayQueueUtil redisDelayQueueUtil;
    @Resource
    private EnterpriseOrderService enterpriseOrderService;

    @Override
    public void run(String... args) {
        ScheduledThreadPoolExecutor executorService = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), new BasicThreadFactory.Builder().namingPattern("redisDelay-schedule-pool-%d").daemon(true).build());
        executorService.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                while (true) {
                    try {
                        String orderSn = redisDelayQueueUtil.getDelayQueue(CacheConstants.ENTERPRISE_ORDER_CREATE_DELAY_QUEUE_KEY);
                        log.info("企业团餐，套餐购买Redis延迟队列触发msg={}", orderSn);
                        enterpriseOrderService.orderCancel(orderSn);
                    } catch (InterruptedException e) {
                        log.error("(Redis延迟队列异常中断) {}", e.getMessage());
                    }
                }
            }
        }, 0, 1, TimeUnit.SECONDS);// 每秒检测一次
    }
}

